package LeetCode;

public class LC_640_SolvetheEquation {

    public static void main(String[] args) {

    }

    public class Solution {
        public String solveEquation(String e) {
            e = e.replace('+', '#');
            String[] ss = e.split("=");
            int[] r1 = get(ss[0]);
            int[] r2 = get(ss[1]);
            int xc = r1[1] - r2[1], cst = r1[0] - r2[0];
            if (xc == 0 && cst == 0)
                return "Infinite solutions";
            else if (xc == 0)
                return "No solution";
            else
                return "x=" + (-cst / xc);
        }

        int[] get(String ss) {
            String[] ss1 = ss.split("#");
            int cst = 0, xc = 0;
            for (String s : ss1) {
                int cst1 = 0, xc1 = 0;
                String[] t = s.split("-");
                if (t[0].indexOf('x') == -1) {
                    if (!"".equals(t[0]))
                        cst1 += Integer.valueOf(t[0]);
                } else {
                    String tmp = t[0].substring(0, t[0].length() - 1);
                    xc1 += "".equals(tmp) ? 1 : Integer.valueOf(tmp);
                }
                for (int i = 1; i < t.length; i++) {
                    if (t[i].indexOf('x') == -1) {
                        if (!"".equals(t[i]))
                            cst1 -= Integer.valueOf(t[i]);
                    } else {
                        String tmp = t[i].substring(0, t[i].length() - 1);
                        xc1 -= "".equals(tmp) ? 1 : Integer.valueOf(tmp);
                    }
                }
                cst += cst1;
                xc += xc1;
            }
            return new int[]{cst, xc};
        }
    }

    public class Solution_2 {
        public String solveEquation(String equation) {
            String[] parts = equation.split("=");
            int[] left = evaluate(parts[0]);
            int[] right = evaluate(parts[1]);
            if (left[0] == right[0] && left[1] == right[1]) return "Infinite solutions";
            else if (left[0] == right[0]) return "No solution";
            return "x=" + (right[1] - left[1]) / (left[0] - right[0]);
        }

        private int[] evaluate(String part) {
            int[] result = new int[2];
            String[] tokens = part.split("(?=[+-])");
            for (String token : tokens) {
                if (token.equals("+x") || token.equals("x")) result[0]++;
                else if (token.equals("-x")) result[0]--;
                else if (token.contains("x")) {
                    result[0] += Integer.parseInt(token.substring(0, token.length() - 1));
                } else {
                    result[1] += Integer.parseInt(token);
                }
            }
            return result;
        }
    }

}